<template>
	<view class="container">
		<view class="page-body">
			<uni-forms ref="formRef" :model="formData" :rules="rules" validate-trigger="submit" label-position="top">
				<view class="form-header">
					<text class="form-title">新增学生</text>
					<text class="form-subtitle">创建一条学生记录</text>
				</view>

				<!-- 学生姓名 -->
				<uni-forms-item name="name" label="学生姓名" required class="form-item standard-label-item">
					<uni-easyinput v-model="formData.name" placeholder="请输入学生姓名" trim="both" />
				</uni-forms-item>

				<!-- 年级 -->
				<uni-forms-item name="grade" label="年级" required class="form-item standard-label-item">
					<picker @change="onGradeChange" :value="gradeIndex" :range="gradeOptions">
						<view class="picker-input">
							<text>{{ formData.grade || '请选择年级' }}</text>
							<uni-icons type="down" size="16" color="#8898AA"></uni-icons>
						</view>
					</picker>
				</uni-forms-item>

				<!-- 班级 -->
				<uni-forms-item name="class" label="班级" required class="form-item standard-label-item">
					<uni-easyinput v-model="formData.class" placeholder="请输入班级" trim="both" />
				</uni-forms-item>

				<!-- 家长姓名 -->
				<uni-forms-item name="parent_name" label="家长姓名" class="form-item custom-label-item">
					<template #label>
						<view class="custom-label">
							<text>家长姓名</text>
							<text class="optional-text">（选填）</text>
						</view>
					</template>
					<uni-easyinput v-model="formData.parent_name" placeholder="请输入家长姓名" trim="both" />
				</uni-forms-item>

				<!-- 家长电话 -->
				<uni-forms-item name="parent_phone" label="家长电话" class="form-item custom-label-item">
					<template #label>
						<view class="custom-label">
							<text>家长电话</text>
							<text class="optional-text">（选填）</text>
						</view>
					</template>
					<uni-easyinput v-model="formData.parent_phone" placeholder="请输入家长电话" type="number" maxlength="11" />
				</uni-forms-item>

				<!-- 学生状态 -->
				<uni-forms-item name="status" label="学生状态" class="status-form-item standard-label-item">
					<view class="status-selection">
						<view class="status-option" :class="{'status-active': formData.status === 1}"
							@click="formData.status = 1">
							<text>在读</text>
						</view>
						<view class="status-option" :class="{'status-inactive': formData.status === 0}"
							@click="formData.status = 0">
							<text>退学</text>
						</view>
					</view>
				</uni-forms-item>

				<!-- 提交按钮 -->
				<view class="form-actions">
					<button class="cancel-button" @click="handleCancel">
						<view class="button-content">
							<text>取消</text>
						</view>
					</button>
					<button class="submit-button" @click="handleSubmit">
						<view class="button-content">
							<text>保存</text>
							<uni-icons type="checkmarkempty" size="18" color="#FFFFFF"></uni-icons>
						</view>
					</button>
				</view>
			</uni-forms>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		nextTick
	} from 'vue';

	import {
		gradeOptions,
		classOptions,
		statusOptions,
		studentRules,
		getGradeIndex,
		getClassIndex
	} from '@/common/student-options.js';

	// 表单数据
	const formData = reactive({
		name: '',
		grade: '',
		class: '',
		parent_name: '',
		parent_phone: '',
		status: 1
	});

	// 表单验证规则
	// 注意：我们在提交时会对选填字段添加默认值处理
	// 前端不对选填字段进行必填验证，而是在提交前填充默认值
	const rules = studentRules;

	// 表单引用
	const form = ref(null);

	// 选择器索引
	const gradeIndex = ref(-1);
	const classIndex = ref(-1);

	// 挂载后获取表单引用
	onMounted(() => {
		// 设置默认年级
		gradeIndex.value = 0;
		formData.grade = gradeOptions[0];

		// 获取表单引用
		nextTick(() => {
			if (typeof uni !== 'undefined' && uni.$refs && uni.$refs.formRef) {
				form.value = uni.$refs.formRef;
			}
		});
	});

	// 年级选择器变化
	function onGradeChange(e) {
		gradeIndex.value = e.detail.value;
		formData.grade = gradeOptions[gradeIndex.value];
	}

	// 表单提交
	async function handleSubmit() {
		try {
			// 先尝试直接获取组件实例
			const formInstance = uni.$refs?.formRef;

			if (formInstance && typeof formInstance.validate === 'function') {
				// 使用组件实例验证
				try {
					const validateResult = await formInstance.validate();
					if (validateResult.valid) {
						await submitFormData();
					}
				} catch (validationError) {
					console.error('表单验证失败:', validationError);
					uni.showToast({
						title: '请检查表单填写是否正确',
						icon: 'none'
					});
				}
			} else {
				// 如果无法获取表单实例或者验证方法，直接提交
				await submitFormData();
			}
		} catch (e) {
			console.error('提交过程中出错:', e);
			uni.showToast({
				title: '提交失败，请重试',
				icon: 'none'
			});
		}
	}

	// 提交表单数据
	async function submitFormData() {
		// 显示加载提示
		uni.showLoading({
			title: '保存中...',
			mask: true
		});

		try {
			// 直接使用原始表单数据，不添加默认值
			const submitData = {
				...formData
			};
			
			console.log('准备提交的学生数据:', JSON.stringify(submitData));

			// 调用云对象保存学生信息
			const studentCloud = uniCloud.importObject('student');
			const result = await studentCloud.createStudent(submitData);
			console.log('创建学生结果:', result);

			// 保存成功提示
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			});

			// 跳转到学生列表页面
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/student/index'
				});
			}, 1500);
		} catch (error) {
			console.error('保存学生信息失败:', error);
			console.error('错误详情:', JSON.stringify(error));
			uni.showToast({
				title: error.message || '保存失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	}

	// 取消
	function handleCancel() {
		uni.navigateBack({
			delta: 1
		});
	}
</script>

<style>
	.container {
		padding: 0;
		background: linear-gradient(165deg, #F8F9FC, #F0F4F8);
		min-height: 100vh;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}

	.page-body {
		padding: 24px 20px;
		flex: 1;
		max-width: 640px;
		margin: 0 auto;
		width: 100%;
		box-sizing: border-box;
	}

	.form-header {
		margin-bottom: 36px;
		position: relative;
		padding-bottom: 16px;
		border-bottom: 1px solid rgba(233, 236, 239, 0.7);
	}

	.form-header::after {
		content: '';
		position: absolute;
		bottom: -1px;
		left: 0;
		width: 60px;
		height: 3px;
		background: linear-gradient(90deg, #0A6CFF, rgba(10, 108, 255, 0.5));
		border-radius: 3px;
	}

	.form-title {
		font-size: 26px;
		font-weight: 600;
		color: #172B4D;
		letter-spacing: -0.5px;
		line-height: 1.3;
		position: relative;
		display: block;
		margin-bottom: 8px;
	}

	.form-subtitle {
		font-size: 15px;
		color: #8898AA;
		letter-spacing: -0.2px;
		font-weight: 450;
	}

	.form-item {
		margin-bottom: 10px;
	}

	.picker-input {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 46px;
		padding: 0 14px;
		background-color: #FFFFFF;
		border: 1px solid #E9ECEF;
		border-radius: 10px;
		transition: all 0.3s ease;
		box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.01), 0 1px 2px rgba(0, 0, 0, 0.02);
	}

	.picker-input:active {
		background-color: #F8F9FC;
		border-color: #0A6CFF;
		transform: scale(0.995);
		box-shadow: 0 0 0 3px rgba(10, 108, 255, 0.15), inset 0 2px 4px rgba(0, 0, 0, 0.01);
	}

	.picker-input text {
		font-size: 15px;
		color: #172B4D;
		font-weight: 450;
	}

	/* 状态选择器自定义样式 */
	.status-form-item {
		margin-top: 0px;
		margin-bottom: 10px;
	}

	.status-selection {
		display: flex;
		margin-top: 0px;
		/* 减少顶部间距，与其他字段保持一致 */
		width: 100%;
		gap: 12px;
	}

	.status-option {
		flex: 1;
		height: 46px;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #F8F9FC;
		border: 1px solid #E9ECEF;
		border-radius: 23px;
		padding: 6px 10px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
		transition: all 0.25s ease;
		position: relative;
		overflow: hidden;
		max-width: 150px;
		cursor: pointer;
	}

	.status-option:active {
		transform: scale(0.98);
		opacity: 0.9;
	}

	.status-option text {
		font-size: 15px;
		font-weight: 600;
		color: #8898AA;
		transition: all 0.25s ease;
		text-align: center;
	}

	.status-option.status-active {
		background-color: rgba(45, 206, 137, 0.15);
		border: 0;
		transform: scale(1.02);
		box-shadow: 0 4px 10px rgba(45, 206, 137, 0.2), inset 0 0 0 1px rgba(45, 206, 137, 0.5);
	}

	.status-option.status-inactive {
		background-color: rgba(245, 54, 92, 0.15);
		border: 0;
		transform: scale(1.02);
		box-shadow: 0 4px 10px rgba(245, 54, 92, 0.2), inset 0 0 0 1px rgba(245, 54, 92, 0.5);
	}

	.status-option.status-active::after,
	.status-option.status-inactive::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100%;
		border-radius: 23px;
		z-index: -1;
		opacity: 0.1;
	}

	.status-option.status-active::after {
		background: linear-gradient(to bottom, #2DCE89, transparent);
	}

	.status-option.status-inactive::after {
		background: linear-gradient(to bottom, #F5365C, transparent);
	}

	.status-option.status-active text {
		color: #2DCE89;
		font-weight: 700;
		text-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);
	}

	.status-option.status-inactive text {
		color: #F5365C;
		font-weight: 700;
		text-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);
	}

	/* 表单动作 */
	.form-actions {
		display: flex;
		justify-content: space-between;
		margin-top: 36px;
		padding: 0;
		gap: 12px;
	}

	.cancel-button {
		flex: 1;
		background-color: rgba(240, 242, 246, 0.9);
		color: #8898AA;
		border: 1px solid #D1D9E6;
		border-radius: 8px;
		height: 44px;
		font-size: 15px;
		font-weight: 500;
		transition: all 0.2s ease;
		letter-spacing: 0;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
		min-width: 100px;
		padding: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		text-align: center;
		position: relative;
		overflow: hidden;
	}

	.cancel-button .button-content {
		color: #8898AA;
	}

	.cancel-button:active {
		background-color: #E9ECEF;
		transform: translateY(1px);
		box-shadow: none;
		border-color: #C8D0DD;
	}

	.cancel-button:active .button-content {
		color: #68778D;
	}

	.submit-button {
		flex: 1;
		background: linear-gradient(135deg, #0A6CFF, #0057E3);
		color: #FFFFFF;
		border-radius: 8px;
		height: 44px;
		font-size: 15px;
		font-weight: 500;
		box-shadow: 0 3px 10px rgba(10, 108, 255, 0.25);
		transition: all 0.2s ease;
		border: none;
		letter-spacing: 0;
		position: relative;
		overflow: hidden;
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 100px;
		padding: 0;
	}

	.button-content {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
	}

	.button-content text {
		margin-right: 6px;
		line-height: 1;
	}

	.button-icon {
		display: none;
	}

	.submit-button::after {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(to bottom, rgba(255, 255, 255, 0.1), transparent);
		opacity: 0.5;
		transition: opacity 0.2s ease;
	}

	.submit-button:active {
		transform: translateY(1px);
		box-shadow: 0 2px 6px rgba(10, 108, 255, 0.2);
		background: linear-gradient(135deg, #0057E3, #0048C4);
	}

	.submit-button:active::after {
		opacity: 0;
	}

	/* 表单项样式覆盖 */
	:deep(.uni-forms-item__inner) {
		padding-bottom: 16px;
	}

	:deep(.uni-forms-item__label) {
		font-size: 15px;
		font-weight: 600;
		color: #172B4D;
		margin-bottom: 2px;
		letter-spacing: -0.2px;
		padding-left: 4px;
		padding-bottom: 0;
		max-width: 100%;
		overflow: visible;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	:deep(.uni-forms-item__label-text) {
		display: inline-block;
		align-items: center;
		width: auto;
		max-width: 100%;
	}

	:deep(.uni-forms-item__required) {
		color: #F5365C;
	}

	:deep(.uni-forms-item__error) {
		padding-left: 4px;
		font-size: 13px;
		color: #F5365C;
		margin-top: 6px;
		letter-spacing: -0.1px;
		opacity: 0.9;
	}

	:deep(.uni-easyinput__content) {
		height: 46px;
		background-color: #FFFFFF;
		border: 1px solid #E9ECEF;
		border-radius: 10px;
		transition: all 0.3s ease;
		box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.01), 0 1px 2px rgba(0, 0, 0, 0.02);
	}

	:deep(.uni-easyinput__content-input) {
		font-size: 15px;
		color: #172B4D;
		padding: 0 12px;
		font-weight: 450;
	}

	:deep(.uni-easyinput__placeholder-class) {
		font-size: 15px;
		color: #A0AEC0;
		font-weight: 400;
	}

	:deep(.uni-easyinput__content:focus-within) {
		border-color: #0A6CFF;
		box-shadow: 0 0 0 3px rgba(10, 108, 255, 0.15), inset 0 2px 4px rgba(0, 0, 0, 0.01);
	}

	:deep(.uni-forms-item:last-child .uni-forms-item__inner) {
		padding-bottom: 0;
	}

	/* 添加阴影效果提升层次感 */
	:deep(.uni-forms) {
		background: rgba(255, 255, 255, 0.4);
		border-radius: 16px;
		padding: 32px;
		box-shadow: 0 16px 40px rgba(0, 0, 0, 0.06);
		backdrop-filter: blur(10px);
		border: 1px solid rgba(255, 255, 255, 0.6);
	}

	@media screen and (max-width: 375px) {
		:deep(.uni-forms) {
			padding: 24px 16px;
		}

		.status-option {
			height: 50px;
		}
	}

	/* 自定义标签样式 - 家长姓名/电话 */
	.custom-label {
		display: flex;
		align-items: center;
		flex-wrap: nowrap;
		font-size: 15px;
		font-weight: 600;
		color: #172B4D;
		margin-bottom: 8px;
		/* 进一步增大底部间距 */
	}

	.optional-text {
		font-size: 13px;
		color: #8898AA;
		font-weight: 400;
		margin-left: 4px;
		white-space: nowrap;
	}

	/* 专门针对使用自定义标签的表单项（家长姓名/电话） */
	.custom-label-item :deep(.uni-forms-item__content) {
		margin-top: 0px;
	}

	.custom-label-item :deep(.uni-forms-item__label) {
		padding-bottom: 0;
		margin-bottom: 0px;
		/* 重置标签底部间距 */
	}

	/* 标准标签表单项间距（学生姓名/年级/班级） */
	.standard-label-item :deep(.uni-forms-item__label) {
		margin-bottom: 0px;
		/* 保持较小的间距 */
	}

	.standard-label-item :deep(.uni-forms-item__content) {
		margin-top: 0px;
		/* 保持较小的间距 */
	}
</style>